package com.qs.commontools.common.service;

import com.qs.commontools.constants.StringConstant;
import com.qs.commontools.common.exception.LengthErrorException;

import java.util.Random;

/**
 * 字符串的数据处理
 * @author qiusuo
 * @since 2021-09-23
 */
public class StringService {

    /**
     * 获取验证码，指定生成长度
     * @return
     */
    public static String verification(Integer num) throws LengthErrorException {
        if (num <= 0){
            throw new LengthErrorException("验证码生成长度不能小于1");
        }
        Integer len = StringConstant.CODE_SEQUENCE.length;
        Random random =new Random();
        StringBuffer sb=new StringBuffer();
        int count=0;
        while(true){
            //随机产生一个下标，通过下标取出字符数组对应的字符
            char c = StringConstant.CODE_SEQUENCE[random.nextInt(len)];
            //假设取出来的字符在动态字符串中不存在，代表没有重复
            if (sb.indexOf(c + "") == -1) {
                sb.append(c);
                count++;
                if (count == num) {
                    break;
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取验证码，指定生成内容
     * @return
     */
    public static String verification(Integer num,char[] code) throws LengthErrorException {
        if (num <= 0) {
            throw new LengthErrorException("验证码生成长度不能小于1");
        }
        Integer len = code.length;
        if (len == 0) {
            throw new LengthErrorException("指定验证码生成的字节数组长度不能为0");
        }
        Random random =new Random();
        StringBuffer sb=new StringBuffer();
        int count=0;
        while(true){
            //随机产生一个下标，通过下标取出字符数组对应的字符
            char c = code[random.nextInt(len)];
            //假设取出来的字符在动态字符串中不存在，代表没有重复
            if (sb.indexOf(c + "") == -1) {
                sb.append(c);
                count++;
                if (count == num) {
                    break;
                }
            }
        }
        return sb.toString();
    }


}
